package terminal.model;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import terminal.interfaces.ISerialPort;

/**
 * Created on Dec 26, 2012
 * @author P. Podwapinski <p.podwapinski@gmail.com>
 */
public class KeyEventToSerialPortProxy extends KeyAdapter {
    
    /**
     * Constructor
     * @param serialPort SerialPort implementation reference used to send 
     * received characters
     */
    public KeyEventToSerialPortProxy( ISerialPort serialPort )
    {
        m_serialPort = serialPort;
    }
    
    @Override public void keyTyped( KeyEvent e )
    {
        final char character = e.getKeyChar();
        
        if ( KeyEvent.CHAR_UNDEFINED != character )
        {
            writeKeyToSerial( character );    
        }
    }
    
    /**
     * If SerialPort has been opened this method will send a given character
     * @param character to be sent
     */
    private void writeKeyToSerial( char character )
    {
        if ( null != m_serialPort )
        {            
            if ( m_serialPort.isOpened() )
            {
                m_serialPort.writeChar( character );
            }
        } 
    }
    
    /**
     * SerialPort instance reference
     */
    ISerialPort m_serialPort;
}
